/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2019-12-07 16:44
 */
package com.yao.common.resp;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Collection;

/**
 * 接口统一返回对象
 * 
 * @author yaoyuming
 * @date 2019/12/07 16:44
 */
@Data
@Accessors(chain = true)
public class ApiResponse<T> {

    /**
     * 返回代码 0-成功 1-失败， 其他...
     */
    private long code;

    /**
     * 返回信息
     */
    private String message;

    /**
     * 返回对象
     */
    private T data;

    public static ApiResponse build() {
        return new ApiResponse();
    }

    public static ApiResponse build(ApiErrorCode apiErrorCode) {
        return build().setCode(apiErrorCode.getCode()).setMessage(apiErrorCode.getMsg());
    }

    public static ApiResponse success() {
        return build(ApiErrorCode.SUCCESS);
    }

    public static ApiResponse fail() {
        return build(ApiErrorCode.FAILED);
    }

    public static ApiResponse fail(String errMsg) {
        ApiResponse fail = fail();
        if (StrUtil.isNotEmpty(errMsg)) {
            fail.setMessage(errMsg);
        }
        return fail;
    }

    public static <T> ApiResponse success(T data) {

        if (ObjectUtil.isNotNull(data)) {
            if (Collection.class.isInstance(data)) {
                return success().setData(JSONUtil.parseArray(JSON.toJSONString(data)));
            } else {
                return success().setData(JSONUtil.parseObj(JSON.toJSONString(data)));
            }
        } else {
            return success().setData(data);
        }
    }

}